package com.geline.wordtool.handler;

import cn.hutool.core.util.StrUtil;
import com.geline.wordtool.domain.TableColumn;
import com.geline.wordtool.domain.TableInfo;
import com.geline.wordtool.domain.TableOne;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * mysql表信息处理类
 *
 * @author: mx
 * @date: 2024-12-04 09:39
 */
@Slf4j
public class MysqlTableInfoHandler implements TableInfoHandler{

    private JdbcTemplate jdbcTemplate;
    private String dbName;

    public MysqlTableInfoHandler(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
        try {
            Connection connection = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
            String url = connection.getMetaData().getURL();
            //"jdbc:mysql://101.133.193.94:3306/newoa-gdnyt4?useUnicode=true"
            url = url.replace("jdbc:mysql://", "");
            this.dbName = url.substring(url.indexOf("/")+1, url.indexOf("?"));
            log.info("<<<<<< {} >>>>>>", dbName);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<TableInfo> getTableInfoList(String tableNameStarts, String excludeTableChars) {
        String sql = String.format("SELECT TABLE_NAME, TABLE_COMMENT FROM information_schema.tables WHERE TABLE_SCHEMA='%s'", this.dbName);
        if(StrUtil.isNotBlank(tableNameStarts)){
            List<String> list = Arrays.asList(tableNameStarts.split(","));
            StringBuffer sb = new StringBuffer();
            boolean first = true;
            for(String start : list){
                if(first){
                    sb.append("TABLE_NAME like '%"+start+"%'");
                    first = false;
                }else {
                    sb.append(" or TABLE_NAME like '%"+start+"%'");
                }
            }
            sql = String.format("%s and (%s)", sql, sb.toString());
        }
        if(StrUtil.isNotBlank(excludeTableChars)){
            List<String> list = Arrays.asList(excludeTableChars.split(","));
            StringBuffer sb = new StringBuffer();
            for(String start : list){
                sb.append(" and TABLE_NAME not like '%"+start+"%'");
            }
            sql = String.format("%s%s", sql, sb.toString());
        }
        log.debug(">>>> TableInfo sql = {}", sql);
        List<TableInfo> tableInfos = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TableInfo.class));
        return tableInfos;
    }

    @Override
    public List<TableOne> getTableOneList(String tableNameStarts, String excludeTableChars) {
        List<TableOne> oneList = new ArrayList<>();
        List<TableInfo> infoList = getTableInfoList(tableNameStarts, excludeTableChars);
        int index = 0;
        for(TableInfo bean : infoList){
            String currTableName = bean.getTableName();
            String sql = String.format("SELECT COLUMN_KEY, COLUMN_NAME as name, IS_NULLABLE as null_char, DATA_TYPE, COLUMN_TYPE as full_type, COLUMN_COMMENT as remark, COLUMN_DEFAULT as def_value FROM information_schema.COLUMNS WHERE table_schema='%s' AND table_name='%s' order by ORDINAL_POSITION", dbName, currTableName);
            log.debug(">>>> TableOne sql = {}", sql);
            List<TableColumn> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(TableColumn.class));
            if(list!=null && list.size()>0){
                TableOne tableOne = new TableOne();
                tableOne.setIndex(++index);
                tableOne.setTableName(currTableName);
                tableOne.setTableComment(bean.getTableComment());
                tableOne.setColumnList(list);
                oneList.add(tableOne);
            }
        }
        return oneList;
    }
}
